<template>
    <Dialog title="服务合并" :show="true" @close="cancel" :width="800" :height="430" :left="uiLeft" :top="uiTop">
        <div class="box">
            <div class="mergemodel">
                <div class="mergemodel_top">
                    <div class="mergemodel_list">
                        <div class="mergemodel_list_head">
                            <div class="mergemodel_list_head_index">序号</div>
                            <div class="mergemodel_list_head_url">服务地址</div>
                            <div class="mergemodel_list_head_change"><span style="cursor:pointer;"
                                    @click.stop="addModelUrl" title="添加服务地址" @mouseenter="hoverliIndex = true"
                                    @mouseleave="hoverliIndex = false"><es-icon :name="'tianjia'"
                                        :color="hoverliIndex ? '#647bff' : '#575B66'" :size="13" /></span></div>
                        </div>
                        <div class="mergemodel_list_data">
                            <div class="mergemodel_list_data_input" v-for="(item, index) in modelListsData ">
                                <div class="mergemodel_list_head_index">{{ index + 1 }}</div>
                                <div class="mergemodel_list_head_url"><input type="text" :value="item"
                                        @input="changeValue($event, index)"></div>

                                <div class="mergemodel_list_head_change"><span style="cursor:pointer;"
                                        @click.stop="deleteModelUrl(index)" title="删除服务地址"
                                        @mouseenter="hoverlideleteIndex = index"
                                        @mouseleave="hoverlideleteIndex = -2"><es-icon :name="'shanchu_2'"
                                            :color="hoverlideleteIndex === index ? '#647bff' : '#575B66'"
                                            :size="15" /></span>
                                </div>
                                <div class="mergemodel_list_head_tip" :title="getTipMessage(index)">{{
        getTipMessage(index)
    }}</div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <iframe :src="iframeSrc" frameborder="0" @load="loadIframe" ref="mainIframe"
                            style="width:100%; height:100%;cursor: not-allowed"></iframe>
                    </div>
                </div>
                <div class="mergemodel_bottom">
                    <el-button @click="generate">生成</el-button>
                    <el-button @click="copy">复制</el-button>
                    <el-button @click="download">下载</el-button>
                </div>

            </div>
        </div>
    </Dialog>
    <TooltipCom v-if="currentDialog == 'delete'" :content="'确认删除这一个服务地址吗？'" :title="'删除'" :isVisible="true"
        @close="currentDialog = undefined" @confirm="deleteConfirm" />
</template>
<script setup lang="ts">
import Dialog from "@/components/Dialog.vue";
import { MenuItem } from "@/scripts/dataTypes";
import { onMounted, ref, onBeforeUnmount, computed, watch, shallowRef } from "vue";
import { getProjectManager } from "@/scripts/getProjectManager";
import {
    createVueDisposer,
    toVR,
} from "vue-xe2-plugin/dist-node/components/xe2/tools";
import { ElMessage } from "element-plus";
// import { FileHandleType, getSaveFileHandle, saveFile } from "xbsj-xe2/dist-node/xe2-base-objects";
import { FileHandleType } from "xbsj-xe2/dist-node/xe2-base-objects";
import { getSaveFileHandle, saveFile } from "@/scripts/utils";

import { JsonValue } from "xbsj-renderer/dist-node/xr-base-utils";
import { merge3dTilesServer } from "esobjs-xe2-plugin/dist-node/esobjs-xe2-plugin-main";
import { loadGifFrames, SceneObject } from "xbsj-xe2/dist-node/xe2-utils";
import TooltipCom from "@/components/common/TooltipCom.vue";

const uiLeft = document.body.clientWidth / 2 - 800 / 2;
const uiTop = ref(60);

const emits = defineEmits(["close"]);
const cancel = () => {
    emits("close");
};

const d = createVueDisposer(onBeforeUnmount);
const objm = getProjectManager();
const cimrtsSceneTreeWrapper = objm.cimrtsSceneTreeWrapper
const cimrtsManager = objm.cimrtsManager

const hoverlideleteIndex = ref(-2)
const hoverliIndex = ref(false)
const modelListsData = ref<any[]>(['', ''])
const tipListsData = ref<any[]>([])

const getAssetsDir = () => {
    return SceneObject.context.getEnv(`vue-xe2-plugin-assets-dir`);
}
const iframeSrc = getAssetsDir() + '/monaco-editor/json-editor.html';
const changeValue = (event: any, index: number) => {
    tipListsData.value = []
    const v = event.target.value
    modelListsData.value[index] = v
}
const addModelUrl = () => {
    tipListsData.value = []
    modelListsData.value.push('')
}

// 当前打开的弹框组件
const currentDialog = ref<undefined | string>(undefined);
const deleteIndex = ref(-1)

const deleteModelUrl = (index: number) => {
    tipListsData.value = []
    deleteIndex.value = index
    currentDialog.value = "delete"
}

// 删除 弹出框确定按钮
const deleteConfirm = () => {
    modelListsData.value.splice(deleteIndex.value, 1)
    currentDialog.value = undefined

}

const getTipMessage = (index: number) => {
    let info = ''
    tipListsData.value.forEach((item) => {
        if (index === item.index) {
            info = item.message
            return
        }
    })
    return info
}
const generate = () => {//生成
    if (modelListsData.value.length < 2) {
        ElMessage.error('请填入至少两个服务地址')
        return
    }
    let a = 0
    modelListsData.value.forEach(item => {
        if (item === '') {
            a++
        }
    })
    if (a > 0) {
        ElMessage.error('服务地址不能为空')
        return
    }
    merge3dTilesServer(modelListsData.value).then(async res => {
        if (res.state === 'success') {
            if (res.tilesUrl) {
                tipListsData.value = []
                ElMessage.success('生成成功')
                await setJson(JSON.stringify(res.tilesUrl, undefined, '    '))
            }
        } else {
            if (res.info) {
                tipListsData.value = res.info
            }
            if (res.tilesUrl) {
                await setJson(JSON.stringify(res.tilesUrl, undefined, '    '))
            } else {
                await setJson(JSON.stringify('', undefined, '    '))
            }
            ElMessage.error('存在错误服务，请检查')
            return
        }
    }).catch(error => {
        ElMessage.error(error)
        console.log('error', error);

    })
}

async function copyClipboard(text: string) {//复制
    navigator.clipboard.writeText(text)
        .then(function () {
            ElMessage.success('复制成功');
        }, function (e) {
            ElMessage.error(`复制失败 error:${e}`);
        });
}

const copy = async () => {//复制
    try {
        const str = await getJson()
        copyClipboard(str)

        // const input = document.createElement('input');
        // input.value = str;
        // document.body.appendChild(input);
        // input.select();
        // document.execCommand('copy');
        // document.body.removeChild(input);

        // ElMessage.success('复制成功');

    } catch (error) {
        console.log('JSON格式错误!!!', error);
        ElMessage.error(`JSON格式错误！ error: ${error}`);
        return
    }

}
const download = async () => {//下载
    try {
        const str = await getJson()
        const json = JSON.parse(str);
        saveAs(json, 'tileset');
    } catch (error) {
        console.log('JSON格式错误!!!', error);
        ElMessage.error(`JSON格式错误！ error: ${error}`);
    }
}
const mergeModelData = ref()
const mainIframe = ref<HTMLIFrameElement>();//json对应的元素

//json编辑器初始化
const loadIframe = async () => {
    // @ts-ignore
    // mainIframe.value && mainIframe.value.contentWindow.monaco.editor.setTheme("vs")

    await setJson(JSON.stringify(mergeModelData.value, undefined, '    '))
}
function setJson(value: string) {//设置json
    return new Promise<void>((resolve, reject) => {
        if (!mainIframe.value || !mainIframe.value.contentWindow) {
            return;
        }
        const setKey = getUuid()
        mainIframe.value.contentWindow.postMessage({ type: 'setJson', id: setKey, value })
        const time = setTimeout(() => {
            removeEventListener('message', messageSetEventWatch, false);
            reject();
        }, 10000);

        const messageSetEventWatch = (messageEvent: MessageEvent<{ type: string, id: string, status: string } | undefined>) => {
            var data = messageEvent.data;
            if (!data || (data.type && data.type !== 'setJsonReturn') || (data.id && data.id !== setKey)) {
                return;
            }
            removeEventListener('message', messageSetEventWatch, false);
            clearTimeout(time)
            if (data.status === 'ok') {
                resolve();
            } else {
                reject();
            }
        }
        addEventListener('message', messageSetEventWatch, false);
    })
}
function getJson() {//获取json上面的内容
    return new Promise<string>((resolve, reject) => {
        if (!mainIframe.value || !mainIframe.value.contentWindow) {
            return;
        }
        const getKey = getUuid()
        mainIframe.value.contentWindow.postMessage({ type: 'getJson', id: getKey })
        const time = setTimeout(() => {
            removeEventListener('message', messageGetEventWatch, false);
            reject();
        }, 10000);

        const messageGetEventWatch = (messageEvent: MessageEvent<{ type: string, id: string, status: string, value: string | undefined } | undefined>) => {
            var data = messageEvent.data;
            if (!data || (data.type && data.type !== 'getJsonReturn') || (data.id && data.id !== getKey)) {
                return;
            }
            removeEventListener('message', messageGetEventWatch, false);
            clearTimeout(time)
            if (data.status === 'ok' && data.value) {
                resolve(data.value);
            } else {
                reject();
            }
        }
        addEventListener('message', messageGetEventWatch, false);
    })

}
function getUuid() {//设置随机id
    var d = new Date().getTime();
    if (window.performance && typeof window.performance.now === "function") {
        d += performance.now();
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return uuid;
}


const saveAs = async (json: JsonValue, name?: string) => {
    try {
        let handle: FileHandleType | undefined
        ElMessage.warning('正在另存为..');
        handle = await getSaveFileHandle('json', name);
        console.log("handle",handle);
        
        if (!handle) return;
        const jsonStr = JSON.stringify(json, undefined, '    ');
        await saveFile(handle, jsonStr);
        ElMessage.success('另存成功!');
    } catch (error) {
        ElMessage.error(`另存失败! error: ${error}`);
    }
}


</script>

<style scoped>
.box {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    /* padding: 15px; */
    display: flex;
    flex-direction: column;
    gap: 20px;
    align-items: center;
}

.mergemodel {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.mergemodel_top {
    width: 100%;
    flex: 1;
    display: flex;
    overflow: hidden;
}

.mergemodel_bottom {
    width: 100%;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-left: -10px;

}

.mergemodel_top>div {
    flex: 1;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    padding: 10px;
    overflow: hidden;
}

.mergemodel_list {
    display: flex;
    flex-direction: column;
    border-right: 1px solid #4a4545;
}


.mergemodel_list_head {
    width: 100%;
    background-color: rgba(242, 243, 246, 0.6);
    border-radius: 4px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    display: flex;
    font-size: 14px;
}

.mergemodel_list_data {
    flex: 1;
    width: 100%;
    overflow: auto;
}

.mergemodel_list_data_input {
    display: flex;
    padding: 5px 0 10px 0;
    box-sizing: border-box;
    position: relative;
}

.mergemodel_list_head_tip {
    position: absolute;
    font-size: 12px;
    top: 30px;
    right: 50px;
    color: red;
    height: 12px;
    overflow: hidden;
}


.mergemodel_list_head_url>input {
    width: 100%;
    height: 100%;
    /* background: rgba(28, 28, 29, 0.6); */
    border-radius: 4px;
    border: 1px solid #999;
    ;
    outline: 0;
    font-size: 14px;
    color: #606266;
    padding-left: 10px;
    box-sizing: border-box;
}

.mergemodel_list_head_url>input:focus {
    border: 1.5px solid #639cff;
    ;

}

.mergemodel_list_head_index {
    width: 50px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-around;
}

.mergemodel_list_head_url {
    flex: 1;
    height: 30px;
    box-sizing: border-box;
}

.mergemodel_list_head_change {
    width: 50px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>